/**
 * 
 */
package org.myontology.users;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import model.Vocabulary;

import org.myontology.controller.SesameSession;
import org.myontology.controller.WebAttributeHolder;
import org.openrdf.model.Literal;
import org.openrdf.model.URI;
import org.openrdf.model.impl.LiteralImpl;
import org.openrdf.model.impl.URIImpl;

/**
 *  @author <a href="michael.hackl@sti2.at">Michael Hackl</a>
 * Project: Myontology - www.myontology.org
 * STI
 */
public class AutoLoginFilter implements Filter {

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		try {
			HttpServletRequest request =(HttpServletRequest)arg0;
			request.getSession(true);
			WebAttributeHolder attributes = new WebAttributeHolder(request);
			String user = Login.CURRENT_USER.getValue(request);
			if (user==null) {
				user = "SandBox-"+Double.toString(System.currentTimeMillis()+Math.random()).hashCode();
				Login.CURRENT_USER.setValue(attributes, user);
				Login.ROLE.setValue(attributes, "user");
				Login.LOGGED_IN.setValue(attributes, true);
				Login.SANDBOX.setValue(attributes, true);
				SesameSession session = new SesameSession();
				session.init();
				Literal sessionId = new LiteralImpl(attributes.getSessionId());
				URI userId = new URIImpl(Vocabulary.USER_NAMESPACE+user);
				session.update(userId, Vocabulary.HASSESSIONID, sessionId);
				session.clean();
				session.finish();
				
			}
		}
		catch(Exception e) {
			
		}
		arg2.doFilter(arg0, arg1);
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
